// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'lvtengweishi-4gvg0d2h59537d91' // 替换为你的云环境 ID
});
const db = cloud.database(); // 初始化数据库引用

// 时间区间和参数区间的映射（温度区间已调整为18-32度）
const timeIntervals = {
  0: {
    "gas(CO2)": [1000, 1050],
    "light": [5, 50],
    "humidity": [60, 65],
    "temperature": [18, 20]
  },
  1: {
    "gas(CO2)": [1010, 1050],
    "light": [5, 50],
    "humidity": [61, 65],
    "temperature": [18, 20]
  },
  2: {
    "gas(CO2)": [1020, 1050],
    "light": [5, 50],
    "humidity": [62, 65],
    "temperature": [18, 20]
  },
  3: {
    "gas(CO2)": [1020, 1040],
    "light": [5, 50],
    "humidity": [62, 65],
    "temperature": [18, 20]
  },
  4: {
    "gas(CO2)": [1010, 1030],
    "light": [5, 100],
    "humidity": [61, 64],
    "temperature": [18, 21]
  },
  5: {
    "gas(CO2)": [1000, 1020],
    "light": [100, 500],
    "humidity": [60, 63],
    "temperature": [20, 23]
  },
  6: {
    "gas(CO2)": [950, 1000],
    "light": [500, 2000],
    "humidity": [58, 62],
    "temperature": [22, 25]
  },
  7: {
    "gas(CO2)": [900, 950],
    "light": [2000, 3500],
    "humidity": [55, 60],
    "temperature": [24, 27]
  },
  8: {
    "gas(CO2)": [850, 900],
    "light": [3500, 4500],
    "humidity": [50, 55],
    "temperature": [26, 29]
  },
  9: {
    "gas(CO2)": [800, 850],
    "light": [4500, 5000],
    "humidity": [48, 53],
    "temperature": [28, 30]
  },
  10: {
    "gas(CO2)": [750, 800],
    "light": [4800, 5000],
    "humidity": [45, 50],
    "temperature": [29, 31]
  },
  11: {
    "gas(CO2)": [720, 780],
    "light": [4800, 5000],
    "humidity": [43, 48],
    "temperature": [30, 32]
  },
  12: {
    "gas(CO2)": [700, 750],
    "light": [4800, 5000],
    "humidity": [40, 45],
    "temperature": [31, 32]
  },
  13: {
    "gas(CO2)": [700, 750],
    "light": [4800, 5000],
    "humidity": [40, 45],
    "temperature": [30, 32]
  },
  14: {
    "gas(CO2)": [720, 770],
    "light": [4500, 4800],
    "humidity": [42, 46],
    "temperature": [29, 31]
  },
  15: {
    "gas(CO2)": [750, 800],
    "light": [4000, 4500],
    "humidity": [43, 48],
    "temperature": [28, 30]
  },
  16: {
    "gas(CO2)": [780, 830],
    "light": [3000, 4000],
    "humidity": [45, 50],
    "temperature": [26, 29]
  },
  17: {
    "gas(CO2)": [820, 880],
    "light": [1500, 3000],
    "humidity": [48, 53],
    "temperature": [24, 27]
  },
  18: {
    "gas(CO2)": [850, 920],
    "light": [500, 1500],
    "humidity": [50, 55],
    "temperature": [22, 25]
  },
  19: {
    "gas(CO2)": [880, 950],
    "light": [50, 500],
    "humidity": [53, 58],
    "temperature": [20, 23]
  },
  20: {
    "gas(CO2)": [900, 970],
    "light": [5, 50],
    "humidity": [55, 60],
    "temperature": [19, 21]
  },
  21: {
    "gas(CO2)": [920, 980],
    "light": [5, 50],
    "humidity": [57, 62],
    "temperature": [18, 20]
  },
  22: {
    "gas(CO2)": [950, 1000],
    "light": [5, 50],
    "humidity": [58, 63],
    "temperature": [18, 20]
  },
  23: {
    "gas(CO2)": [980, 1020],
    "light": [5, 50],
    "humidity": [59, 64],
    "temperature": [18, 20]
  }
};

// 补充：生成随机数的函数（关键缺失部分）
function getRandomValue(min, max) {
  return Math.random() * (max - min) + min;
}

// 生成指定时间范围内的传感器数据（每小时1条，强制UTC+8时区）
function generateSensorData() {
  // 注意：直接使用北京时间字符串（不指定时区时，JS会默认按本地时区解析，这里强制按UTC+8处理）
  const startTime = new Date('2025-07-02T10:00:00+08:00'); // 明确指定UTC+8
  const endTime = new Date('2025-07-06T12:00:00+08:00');   // 明确指定UTC+8

  const data = [];
  let currentTime = new Date(startTime);

  // 循环生成每小时的数据（条件改为 < endTime，避免多生成1条）
  while (currentTime < endTime) {
    const hour = currentTime.getHours(); // 获取当前小时（0-23，基于UTC+8）
    const interval = timeIntervals[hour];

    // 生成UTC+8格式的时间字符串（格式：YYYY-MM-DDTHH:mm:ss+08:00）
    const year = currentTime.getFullYear();
    const month = String(currentTime.getMonth() + 1).padStart(2, '0');
    const day = String(currentTime.getDate()).padStart(2, '0');
    const hours = String(currentTime.getHours()).padStart(2, '0');
    const minutes = String(currentTime.getMinutes()).padStart(2, '0');
    const seconds = String(currentTime.getSeconds()).padStart(2, '0');
    // 拼接为UTC+8格式（带时区标识+08:00）
    const beijingTimeStr = `${year}-${month}-${day}T${hours}:${minutes}:${seconds}+08:00`;

    const record = {
      "humidity": parseFloat(getRandomValue(interval.humidity[0], interval.humidity[1]).toFixed(1)),
      "light": parseFloat(getRandomValue(interval.light[0], interval.light[1]).toFixed(1)),
      "temperature": parseFloat(getRandomValue(interval.temperature[0], interval.temperature[1]).toFixed(1)),
      "gas(CO2)": parseFloat(getRandomValue(interval["gas(CO2)"][0], interval["gas(CO2)"][1]).toFixed(1)),
      "greenhouseID": "01",
      "monitortime": beijingTimeStr // 存储UTC+8格式的时间
    };

    data.push(record);
    // 时间推进1小时（基于UTC+8）
    currentTime = new Date(currentTime.getTime() + 60 * 60 * 1000);
  }

  return data;
}

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext();
  const sensorData = generateSensorData();

  // 按monitortime升序排序并打印日志（验证生成的数据）
  const sortedData = [...sensorData].sort((a, b) => {
    return new Date(a.monitortime) - new Date(b.monitortime);
  });

  console.log('===== 生成的数据（按monitortime升序） =====');
  sortedData.forEach((item, index) => {
    console.log(`第${index + 1}条：`);
    console.log(`时间：${item.monitortime}`);
    console.log(`温度：${item.temperature}°C | 湿度：${item.humidity}% | 光照：${item.light} | CO2：${item["gas(CO2)"]}`);
    console.log('----------------------------------------');
  });
  console.log(`===== 共生成 ${sortedData.length} 条数据 =====`);

  // 存储数据到数据库
  try {
    // 批量插入数据（优化为分批处理，避免并发过高）
    const batchSize = 20;
    const total = sensorData.length;
    let success = 0;

    for (let i = 0; i < total; i += batchSize) {
      const batch = sensorData.slice(i, i + batchSize);
      const promises = batch.map(item => db.collection('Greenhouse_Data').add({ data: item }));
      await Promise.all(promises);
      success += batch.length;
      console.log(`已插入第 ${i + 1}-${Math.min(i + batchSize, total)} 条数据`);
    }

    return {
      success: true,
      message: `已成功生成并存储2025年7月2日10点至7月6日10点的数据（共${success}条）`,
      openid: wxContext.OPENID,
      appid: wxContext.APPID
    };
  } catch (err) {
    console.error('数据存储失败：', err);
    return {
      success: false,
      message: '数据存储失败',
      error: err.message
    };
  }
};